<?php
// WARNING: this will work only in PHP5
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();
if(!defined('ACC_INC')) define(ACC_INC,DOKU_INC.'phpincludes/');

if(!defined('ACCMTL_URL')) define(ACCMTL_URL,'http://www.accmontreal.ca/');
if(!defined('ACCMTL_BASEDIR')) define(ACCMTL_BASEDIR,$_SERVER['DOCUMENT_ROOT'].'/');

if(!defined('ACCMTL_CAL_URL')) define(ACCMTL_CAL_URL,ACCMTL_URL.'@@lang@@/club/calendar/home?ics_id=');

if(!defined('ACCMTL_NEWS_URL')) define(ACCMTL_NEWS_URL,ACCMTL_URL.'@@lang@@/club/news/home?ics_id=');
if(!defined('ACCMTL_ELETTER_URL')) define(ACCMTL_ELETTER_URL,ACCMTL_URL.'eletter/');
if(!defined('ACCMTL_ELETTER_IMGURL')) define(ACCMTL_ELETTER_IMGURL,ACCMTL_ELETTER_URL.'img/');

if(!defined('ACCMTL_ELETTER_DIR')) define(ACCMTL_ELETTER_DIR,ACCMTL_BASEDIR.'eletter/');
if(!defined('ACCMTL_ELETTER_IMGDIR')) define(ACCMTL_ELETTER_IMGDIR,ACCMTL_ELETTER_DIR.'img/');

if(!defined('ACCMTL_ELETTER_LINK_FMT_STYLE')) define(ACCMTL_ELETTER_LINK_FMT_STYLE,'color=#333333;text-decoration:none;');
if(!defined('ACCMTL_ELETTER_LINK_FMT')) define(ACCMTL_ELETTER_LINK_FMT,'<a class=\'toclinkstyle\' href=\'%s\'>%s</a>');
if(!defined('ACCMTL_ELETTER_LINK_FMT2')) define(ACCMTL_ELETTER_LINK_FMT2,'<a class=\'%s\' href=\'%s\'>%s</a>');

if(!defined('ACCMTL_ELETTER_TPL_CSS')) define(ACCMTL_ELETTER_TPL_CSS,ACC_INC.'_eletter_tpl3.css');
if(!defined('ACCMTL_ELETTER_TPL_HTML0')) define(ACCMTL_ELETTER_TPL_HTML0,ACC_INC.'_eletter_tpl3_fr-en.html');
if(!defined('ACCMTL_ELETTER_TPL_HTML1')) define(ACCMTL_ELETTER_TPL_HTML1,ACC_INC.'_eletter_tpl3_en-fr.html');
if(!defined('ACCMTL_ELETTER_TPL_ITEM_HTML')) define(ACCMTL_ELETTER_TPL_ITEM_HTML,ACC_INC.'_eletter_tpl3_item.html');
if(!defined('ACCMTL_ELETTER_TPL_TEXT')) define(ACCMTL_ELETTER_TPL_TEXT,ACC_INC.'_eletter_tpl3.txt');
if(!defined('ACCMTL_ELETTER_TPL_ITEM_TEXT')) define(ACCMTL_ELETTER_TPL_ITEM_TEXT,ACC_INC.'_eletter_tpl3_item.txt');


require_once(ACC_INC.'ACC_Form_Base.php');

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 * @date       2009-02-14
 */
class ACC_Form_eletter_admin extends ACC_Form_Base {

    var $mailTo = 'web@accmontreal.ca';
    var $mailToAllowed = array('web@accmontreal.ca');
    var $mailToField = 'to_email';
    var $mailFromField = 'from_email';
    var $mailFromNameField = 'from_name';
    var $mailSubjectPrefix = '[ACC eLetter Item] ';

    var $mailSubjectFmtName = 'mailSubjectFmt';
    var $mailBodyFmtName = 'mailBodyFmt';

    var $metaFileSuffix = 'eletter';
    var $metaFileid = '__eletter';

    var $tpl_letter_filename = '_eletter_tpl3.html';
    var $tpl_letter_item_filename = '_eletter_tpl3_item.html';

    var $imgWmax = 180;
    var $imgHmax = 180;
    var $imgWmaxWide = 370;

    var $langArray = array(
        'fr' => array(
            'mailSent'       => 'Votre message a &eacute;t&eacute; envoy&eacute;',
            'mailSentError'  => "Erreur d'envoie, SVP contacter l'administrateur a ",
            'more' => 'Plus de details',
            'read_online' => 'Lire cette eLetter en ligne'
        ),
        'en' => array(
            'mailSent'       => 'Your message was sent sucessfully',
            'mailSentError'  => 'There was an error sending your email, please contact the admin at ',
            'more' => 'more info',
            'read_online' => 'Read this eLetter Online',
            'formDescFmt' => 'name eletter_admin
action metafile eletter
Thanks "All worked ok apparently!"
Fieldset "eLetter \'Edit Items\' Selection"
static "You may limit the number of news \'Edit Items\' displayed below with the following selectors."
select "Status" "All|Featured|Not_Hidden|Hidden|Forced_Include|Deleted" =__select_status__ &select_status
date "Date From [YYYY-MM-DD]" "=__date_from__" #20 &select_date_from
date "Date To [YYYY-MM-DD]" "=__date_to__" #20 &select_date_to
submit "Update Selection" &submit_select
Fieldset "eLetter Edit Items"
static "Selected action will be applied to checked items below once you submit the form (Take Action button below)."
select "Action on selected items" "Feature|Force_Include|Hide|Unset_Feature|Unset_Forced_Include|Unset_Hide|Delete|Un-Delete" &eletter_action !
__items_list__
submit "Take Action"  &submit_action
Fieldset "eLetter Production"
static "The eLetter will include NEW and FEATURED items valid in the above selected date range + FORCED_INCLUDE items (if any) of any date (hidden and deleted items will not be included as well as the ones outside date range)"
select "News items to include (nb weeks)" "None|1|2|3|4|5|6|7|8|9" =1 &news_nb_wk
select "Calendar event (full desc) to include (nb weeks) [Note that calendar links are included anyway]" "None|1|2|3|4|5|6|7|8|9" =None &cal_nb_wk
static "You can add a Featured img with legend. This image will appear at the top of eLetter. It is normally used to show an image of the last outing."
file "Featured Img (optional)" &f_img !
textarea "Featured Img Legend En (optional)" x3 #500 &f_img_l_en !
textarea "Featured Img Legend Fr (optionel)" x3 #500 &f_img_l_fr !
yesno "Overwrite existing today\'s eLetter (if any)" &overwrite !
submit "Preview eLetter"  &submit_preview
submit "Produce eLetter"  &submit_produce
',
            'mailSubjectFmt' => ' ',
            'mailBodyFmt' => ' ',
            'error_no_match' => 'We were not able to find a request matching this number/email combination. Please check and try again.',
            'msg_cancel'    => ''
        )
    );
/*
static "Include items valid in the following date range (Note that hidden items will not show; \'forced include\' items outside date range will be included) Items are sorted in chronological order, featured ones apprearing first."
date "Date From [YYYY-MM-DD]" "=__produce_date_from__" #20 &produce_date_from
date "Date To [YYYY-MM-DD]" "=__produce_date_to__" #20 &produce__date_to
*/
    var $sortKey = 'date_to';
    var $selectCriterions = NULL;
    var $checked_uids = NULL;
    var $cancelFields = NULL;
    var $metaFile = NULL;

    /**
     *
     */
    public function _action_show_form($formDescFmtName='formDescFmt') {
        global $ID;
        $this->adminmode = true;
        $showAdminFrom = true;
        if(isset($_GET['acceletteredid']) ||
           isset($_POST['accmtl_eletter_add__']['submit_news_item'])){
            require_once(ACC_INC.'ACC_Form_eletter_base.php');
            $my_contact_form = new ACC_Form_eLetter($this->parent);
            $my_contact_form->adminmode = true;
            $formData = $my_contact_form->_getFormDescData($formDescFmtName);
            if(isset($_GET['acceletteredid'])){
                $this->metaFile = $this->_metaFile_get($this->metaFileid);
                if(isset($this->metaFile[$_GET['acceletteredid']])){
                    $showAdminFrom = false;
                    $my_contact_form->reset = false;
                    $postValues = $my_contact_form->buro->_idnames2idx($formData['data'],$this->metaFile[$_GET['acceletteredid']]);
                } else {
                    msg('Edit Item does not exists:'.hsc($_GET['acceletteredid']),-1);
                }
                $errors = array();
            } else {
                $errors = $my_contact_form->buro->_checkpost($formData['data']);
                if (!count($errors)) {
                    $errors = $my_contact_form->_postcheckpost($formData['data']);
                }
                if(count($errors)) {
                    $showAdminFrom = false;
                    $postValues = $_POST;
                } else {
                    $my_contact_form->_action_ok($formData['data'],'Sucessfully Updated Item: '.$_GET['acceletteredid']);
                }
            }
        }

        if(isset($_GET['acceletterdetails'])){
            echo '<a name="acceletterdetails"></a>';
            $this->metaFile = $this->_metaFile_get($this->metaFileid);
            if(isset($this->metaFile[$_GET['acceletterdetails']])){
                $errors[9999] = 1;
                $details = '';
                foreach($this->metaFile[$_GET['acceletterdetails']] as $k=>$v)
                    $details .= $k.' = '.$v."\n";
                msg('Details: Item For item:'.hsc($_GET['acceletterdetails']).'<br /><pre>'.$details.'</pre>',0);
            } else {
                $errors[9999] = 1;
                msg('Details: Item does not exists:'.hsc($_GET['acceletterdetails']),-1);
            }
        }

        if($showAdminFrom) {
            parent::_action_show_form($formDescFmtName);
        }else{
            echo '<a name="acceletteredititem"></a>';
            msg('Editing item:'.hsc($_GET['acceletteredid']).' :: <a href="?id='.$ID.'#eletter_admin__">Click Here to Cancel Editing</a>',0);
            print($my_contact_form->buro->_htmlform($formData['data'],$errors,false,$postValues));
        }

    }

    /**
     *
     */
    function _getFormDescFieldsVals($formDescFmtName) {
        global $ID;
        //only one possible format, ignore $formDescFmtName

        //@unlink($this->_metaFileName());

        $now = date('Y-m-d');
        $date_to_stamp = mktime(0, 0, 0, date("m")  , date("d"), date("Y")) + 14*24*3600;
        $date_to = date('Y-m-d',$date_to_stamp);

        if(!is_array($this->selectCriterions)) {
            //$values = $this->buro->_collectpost($data);
            if(isset($_POST['eletter_admin__'])) $values = $_POST['eletter_admin__'];
            $this->selectCriterions = array(
                'select_status' => 'Not_Hidden',
                'select_date_from' => $now,
                'select_date_to' => $date_to
                );
/*
,
                'produce_date_from' => $now,
                'produce_date_to' => $date_to
*/
            if(count($values))
                $this->selectCriterions = array_merge($this->selectCriterions,$values);
        }

        $items_list = '';
        $item_fmt = 'leftcheck "__details__" ! &uid__uid__';
        $details_fmt = '<p style=\'float:left;\'><b>__date__ __subject_en__</b> [<a href=\'__details_link__\' title=\'__All_Details__\'>Details</a>][<a href=\'__edit_link__\'>edit</a>]<br />__from_name__ &lt;<a href=\'mailto:__from_email__\'>__from_email__</a>&gt; __from_phone__ <br />[__status__] [id=<acronym title=\'__All_Details2__\'>__uid__</acronym>]</p>__img_xhtml_tag__';

        $this->metaFile = $this->_metaFile_get($this->metaFileid);
        $sortlist = array();
        $keeplist = array();
        foreach($this->metaFile as $uid => $item) {
            $keep = true;
            if(!is_null($this->selectCriterions)) {
                $keep = false;
                if ($this->selectCriterions['select_status'] == 'All' ||
                    ($this->selectCriterions['select_status'] == 'Not_Hidden' && $item['status']!='hidden') ||
                     strtolower($this->selectCriterions['select_status']) == $item['status'])
                    $keep = true;
                if ($item['status']=='pre_deleted'){
                    $keep = false;
                    if ($this->selectCriterions['select_status']=='Deleted') $keep = true;
                }
                if ($keep) {
                    $d_item1 = strtotime($item['date_from']);
                    $d_item2 = strtotime($item['date_to']);
                    $d_min = strtotime($this->selectCriterions['select_date_from']);
                    $d_max = strtotime($this->selectCriterions['select_date_to']);
                    if($d_item2<$d_min || $d_item1>$d_max) $keep = false;
                }
            }
            if($keep){
                if(!isset($item['date']))  $item['date'] = '';

                $sortlist[$uid] = $item[$this->sortKey];
                //
                $item['All_Details'] = '';
                $item['All_Details2'] = '';
                $item['details_link'] = '?id='.$ID.'&acceletterdetails='.$uid.'#acceletterdetails';
                $item['edit_link'] = '?id='.$ID.'&acceletteredid='.$uid.'#acceletteredititem';
                $item['img_xhtml_tag'] = $this->_get_img_tag($item['imgfile'],false,75);
                $details = $this->_str_replace_from_values($details_fmt,$item);
                $keeplist[$uid] =  $this->_str_replace_from_values($item_fmt,array('uid'=>$uid,'details'=>$details));
            }
        }
        if(count($keeplist)) {
            asort($sortlist);
            foreach($sortlist as $k=>$v) $items_list .= $keeplist[$k]."\n";
        } else {
            $items_list = 'static "No news matching your above Selection"';
        }

        return array(
                '__items_list__' => $items_list,
                '__select_status__' => $this->selectCriterions['select_status'],
                '__date_from__' => $this->selectCriterions['select_date_from'],
                '__date_to__' =>  $this->selectCriterions['select_date_to'],
                '__select_date_from__' => $this->selectCriterions['select_date_from'],
                '__select_date_to__' => $this->selectCriterions['select_date_to']
            );
/*
                '__produce_date_from__' => $this->selectCriterions['produce_date_from'],
                '__produce_date_to__' => $this->selectCriterions['produce_date_to']
*/
    }

    /**
     *
     */
    function _get_img_tag($img_id,$online=false,$maxWH=false){
        $imgWmax = $this->imgWmax;
        $imgHmax = $this->imgHmax;
        if($maxWH) {
            $imgWmax = $maxWH;
            $imgHmax = $maxWH;
        }
        if($img_id) {
            $img_url = ml($img_id,array('w'=>$imgWmax),true,'&amp;',true);
            list($ext,$mime,$dl) = mimetype($img_url);
            if(substr($mime,0,5) == 'image'){
                $w = $imgWmax;
                $file = mediaFN($img_id);
                $info = @getimagesize($file); //get original size
                if(is_array($info)) {
                    $w = $info[0];
                    $h = $info[1];
                    if($h>$imgHmax|| $w>$imgWmax) {
                        $ratio = min(min($w,$imgWmax)/$w,min($h,$imgHmax)/$h);
                        $w = round($w*$ratio);
                    }
                }
                if($online===false){
                    $img_url = ml($img_id,array('w'=>$w),true,'&amp;',true);
                } else {
                    $img_filename = date('Y-m-d-').$online.'-'.noNS($img_id);
                    require_once(DOKU_INC.'inc/media.php');
                    $file2 = media_resize_image($file,$ext,$w);
                    if(!@file_exists($file2)) $file2=$file;
                    $filecontent = @io_readFile($file2, false);
                    @io_saveFile(ACCMTL_ELETTER_IMGDIR.$img_filename,$filecontent);
                    $img_url = ACCMTL_ELETTER_IMGURL.$img_filename;
                }
                return '<img style=\'margin:5px;float:left;\' src=\''.$img_url.'\' />';
                    //    '<img class=\'mediaright\' src=\''.$img_url.'\' />';
            }
        }
        return '';
        /*
        if($item['imgfile']){
            require_once DOKU_INC . 'inc/parser/xhtml.php';
            $render = new Doku_Renderer_xhtml();
            list($ext,$mime,$dl) = mimetype($item['imgfile']);
            if(substr($mime,0,5) == 'image' && $render){
                $link = ml($item['imgfile'],array('h'=>50),true,'&amp;',true);
                $link = ml($src,array('id'=>$ID,'cache'=>$cache),($linking=='direct'));
                _media ($src, $title=NULL, $align=NULL, $width=NULL,$height=NULL, $cache=NULL, $render = true);
                if($item['imgfile']) $item['__img_xhtml_tag__'] = $render->_media($item['imgfile'],array('h'=>50),true,'&amp;',true);
            }
        }
        */
    }

    /**
     *
     */
    function _postcheckpost($data) {
        $errors = array();
        $values = $this->buro->_collectpost($data);
        $idx=999;

        if($values['submit_select']){
            $this->selectCriterions = $values;
            //update form desc
            $errors['submit_select'] = 1; //trigger an error to get the form back with updated values
            msg('Updated Selection.',0);

        }
        if($values['submit_action']){
            $this->selectCriterions = $values;

            if (!$values['eletter_action']) {
                $errors['eletter_action'] = 1;
                msg('You must select an Action.',-1);
            }
            $this->checked_uids = array();
            foreach($values as $k=>$v){
                if(substr($k,0,3)=='uid' && $v=='Yes') {
                    $this->checked_uids[] = substr($k,3);
                }
            }
            if(!count($this->checked_uids)) {
                $errors[$idx++] = 1;
                msg('You must select/check one or more item to take action on.',-1);
            }
        }
        if($values['submit_produce']){
            $filename = ACCMTL_ELETTER_DIR.$this->_eletter_name();
            if(@file_exists($filename) && (!isset($values['overwrite']) || strtolower($values['overwrite']) == 'no')) {
                $errors['overwrite'] = 1;
                msg('To replace existing today\'s eLettre file, you must check the "Overwrite" option box.',-1);
            }
        }
        return $errors;
    }

    /**
     *
     */
    function _action_ok($data,$thanks) {
        $values = $this->buro->_collectpost($data);
        if($values['submit_action'] && count($this->checked_uids))
            $thanks = $this->_admin_submit_action($values['eletter_action'],$this->checked_uids,$this->metaFile,$this->metaFileid);
        if($values['submit_preview']) $thanks = $this->_admin_submit_preview($values,$this->metaFile);
        if($values['submit_produce']) $thanks = $this->_admin_submit_produce($values,$this->metaFile);
        return $thanks;
    }

    /**
     *
     */
    function _admin_submit_select() {
    }

    /**
     *
     */
    function _admin_submit_action($action,$checked_uids,$metaFileData,$metaFileId) {
        $msg = '';
        foreach($checked_uids as $uid) {
            switch($action) {
                case 'Feature':
                    $metaFileData[$uid]['status'] = 'featured';
                break;
                case 'Unset_Feature':
                    if ($metaFileData[$uid]['status']=='featured')
                        $metaFileData[$uid]['status'] = 'new';
                break;
                case 'Force_Include':
                    $metaFileData[$uid]['status'] = 'forced_include';
                break;
                case 'Unset_Force_Include':
                    if ($metaFileData[$uid]['status']=='forced_include')
                        $metaFileData[$uid]['status'] = 'new';
                break;
                case 'Hide':
                    $metaFileData[$uid]['status'] = 'hidden';
                break;
                case 'Unset_Hide':
                    if ($metaFileData[$uid]['status']=='hidden')
                        $metaFileData[$uid]['status'] = 'new';
                break;
                case 'Delete':
                    if($metaFileData[$uid]['status']=='pre_deleted'){
                        unset($metaFileData[$uid]);
                    }else{
                        $metaFileData[$uid]['status'] = 'pre_deleted';
                    }
                break;
                case 'Un-Delete':
                    if($metaFileData[$uid]['status']=='pre_deleted')
                        $metaFileData[$uid]['status'] = 'new';
                break;
            }
            $msg .= $uid.', ';
        }
        $ok = $this->_metaFile_save($metaFileData,$metaFileId);
        if ($ok) {
            return 'Did "'.$action.'" on items: '.$msg.'<br />[pending implementation] A notification email was sent.';
        } else {
            msg('Problem taking requested action',-1);
            return '';
        }
    }

    function _sorted_id_selection($metaFileData,$keepDateRange,$keepstatus=false,$nokeepstatus=false){
        if(!$keepstatus) $keepstatus=array();
        if(!$nokeepstatus) $nokeepstatus=array();
        $id_0 = array();
        foreach($metaFileData as $uid => $item) {
            $keep = false;
            if((!count($keepstatus) || in_array($item['status'],$keepstatus)) && !in_array($item['status'],$nokeepstatus)){
                $d_item1 = strtotime($item['date_from']);
                $d_item2 = strtotime($item['date_to']);
                $d_min = strtotime($keepDateRange[0]);
                $d_max = strtotime($keepDateRange[1]);
                if($d_item2>=$d_min && $d_item1<=$d_max)
                    $id_0[$uid] = $item['date_to'];
            }
        }
        asort($id_0);
        return ($id_0);
    }


    /**
     *
     */
    function _admin_submit_preview($postValues,$metaFileData) {
        $email = $this->_admin_submit_preview_produce($postValues,$metaFileData,false);
        $email_css  = @io_readFile(ACCMTL_ELETTER_TPL_CSS,false);
        $msg =  '<p>Preview Action - Below is what the eLetter email would look like.<br />'.
                'You may now <a href="#produce_form__">use the form below</a> to produce  the eLetter email source.</p>'.
                $email.
                '<style type="text/css">'.$email_css.
                '</style><a name="produce_form__"></a>';
        $this->reset = false;
        return $msg;
    }

    /**
     *
     */
    function _stripHTMLtags($txt,$uft8=false){
        //$txt = preg_replace('/<style[^<>]*>.*<\/style>/i','',$txt); //TODO: non greedy pattern matching
        //$txt = preg_replace('/<script[^<>]*>.*<\/script>/i','',$txt); //TODO: non greedy pattern matching
        $txt = str_replace(array('<br />','<br>','<br/>','&#039;'),array("\n","\n","\n","'"), $txt);
        $txt = preg_replace('/<[^<>]+>/','',$txt);
        if($uft8) return html_entity_decode(utf8_decode($txt));
        else return html_entity_decode($txt);
    }

    /**
     *
     */
    function show_event_cal_list($lang){
        $calendars = array(
            'en' => array(
                'courses_en' => 'http://www.google.com/calendar/ical/r0lkpjbvsnkdlk16td3unut6oc%40group.calendar.google.com/public/basic.ics',
                'outings_en' => 'http://www.google.com/calendar/ical/vmu197blcs4fbq8q85upst3an4%40group.calendar.google.com/public/basic.ics',
                'socials_en' => 'http://www.google.com/calendar/ical/g5v8eo634ib03j95ur1sof0grg%40group.calendar.google.com/public/basic.ics'
                ),
            'fr' => array(
                'courses_fr' => 'http://www.google.com/calendar/ical/8b7fgqaqvf5hi69k2s25fapqdo%40group.calendar.google.com/public/basic.ics',
                'outings_fr' => 'http://www.google.com/calendar/ical/do7qlbrl3d4bgh9922dn6rh5a4%40group.calendar.google.com/public/basic.ics',
                'socials_fr' => 'http://www.google.com/calendar/ical/os1n56fgl2k8bgg0d4o3bbp5jk%40group.calendar.google.com/public/basic.ics'
                )
        );

        $calObj =& plugin_load('helper', 'icsshow');
        if (is_null($calObj) || plugin_isdisabled('icsshow')) return '';

        $options = array();
        $options['sort_order'] = array('','old2new');
        //TODO: set dates according to selection
        $options['date0'] = array('','today');
        $options['date_min'] = array('','today');
        $options['date_max'] = array('','today+28');
        $options['dateformat'] = array('','%Y%m%d');
        $options['format'] = array('',"<a class='callinkstyle' href='http://www.accmontreal.ca/".$lang."/club/calendar/home?ics_id=@@uid@@'><b>@@start_date_month@@ @@start_date_day@@</b> @@summary@@</a><br />");
        return $calObj->_render_xhtml($calendars[$lang],$options);
    }


    /**
     *
     */
    function _admin_submit_preview_produce($postValues,$metaFileData,$onlineFormat=false,$txtFormat=false,$inemail=false) {
        require_once(ACC_INC.'ACC_Calendar_Base.php');
        if($txtFormat){
            $tpl_letter = io_readFile(ACCMTL_ELETTER_TPL_TEXT, false);
            $tpl_item = io_readFile(ACCMTL_ELETTER_TPL_ITEM_TEXT, false);
            $tpl_css = '';
        } else {
            if(date('W') % 2) {
                $tpl_letter = io_readFile(ACCMTL_ELETTER_TPL_HTML0, false);
            }else{
                $tpl_letter = io_readFile(ACCMTL_ELETTER_TPL_HTML1, false);
            }
            $tpl_item = io_readFile(ACCMTL_ELETTER_TPL_ITEM_HTML, false);
            $tpl_css = io_readFile(ACCMTL_ELETTER_TPL_CSS, false);
        }

        $eletter_link = ACCMTL_ELETTER_URL.$this->_eletter_name();
        $maxtopitems = 2;

        $id_0 = $this->_sorted_id_selection($metaFileData,array($postValues['select_date_from'],$postValues['select_date_to']),array('featured'),array('hidden','pre_deleted'));
        $id_1 = $this->_sorted_id_selection($metaFileData,array($postValues['select_date_from'],$postValues['select_date_to']),array(),array('featured','hidden','pre_deleted'));
/*
        $id_0 = $this->_sorted_id_selection($metaFileData,array($postValues['produce_date_from'],$postValues['produce_date_to']),array('featured'),array('hidden','pre_deleted'));
        $id_1 = $this->_sorted_id_selection($metaFileData,array($postValues['produce_date_from'],$postValues['produce_date_to']),array(),array('featured','hidden','pre_deleted'));
*/
        $id_2 = $this->_sorted_id_selection($metaFileData,array('1980-01-01','2100-01-01'),array('forced_include'),array('featured','hidden','pre_deleted'));
        $id_1 = array_merge($id_1,$id_2);
        asort($id_1);

        $letter_values = array();
        $letter_values['subtitle'] = '';
        $letter_values['Date'] = date('Y-m-d');
        $letter_values['eletter_link_txt_fr'] = '';
        $letter_values['eletter_link_txt_en'] = '';
        $letter_values['eletter_link'] = '';
        $full_desc = true;
        if(!$onlineFormat) {
            $full_desc = false;
            $letter_values['eletter_link_txt_fr'] = '[Consulter la version complete en ligne]';
            $letter_values['eletter_link_txt_en'] = '[Read the full version online]';
            $letter_values['eletter_link'] = $eletter_link;
        } else {
            $letter_values['eletter_link_txt_fr'] = '[Visiter le site web du CAC Montreal]';
            $letter_values['eletter_link_txt_en'] = '[Go to the ACC Montreal web site]';
            $letter_values['eletter_link'] = ACCMTL_URL;
        }
        $letter_values['titles_anchor_links_en'] = '';
        //$mycalObj = new ACC_Calendar_eletter_activities();
        //$letter_values['calendar_links_en'] = $mycalObj->show('en');
        $letter_values['calendar_links_en'] = $this->show_event_cal_list('en');
        $letter_values['top_part_items_en'] = '';
        $letter_values['bottom_part_items_en'] = '';
        $letter_values['titles_anchor_links_fr'] = '';
        //$mycalObj = new ACC_Calendar_eletter_activities();
        //$letter_values['calendar_links_fr'] = $mycalObj->show('fr');
        $letter_values['calendar_links_fr'] = $this->show_event_cal_list('fr');

		$letter_values['featured_img'] = '';
		$letter_values['featured_img_legend_en'] = '';
		$letter_values['featured_img_legend_fr'] = '';
		if(isset($postValues['f_img']) && $postValues['f_img']) {
			$f_img_id = false;
			if($onlineFormat) $f_img_id = 999;
			$letter_values['featured_img'] = $this->_get_img_tag($postValues['f_img'],$f_img_id,$this->imgWmaxWide);
			$letter_values['featured_img_legend_en'] = $postValues['f_img_l_en'];
			$letter_values['featured_img_legend_fr'] = $postValues['f_img_l_fr'];
		}

        $letter_values['top_part_items_fr'] = '';
        $letter_values['bottom_part_items_fr'] = '';
        $line_sep = '<br />';
        $lt = '&lt;';
        $gt = '&gt;';
        if($inemail){
            $lt = hsc('&lt;');
            $gt = hsc('&gt;');
        }
        if($txtFormat){
            $line_sep = "\n";
            $lt = '';
            $gt = '';
            $letter_values['calendar_links_en'] = $this->_stripHTMLtags($letter_values['calendar_links_en']);
            $letter_values['calendar_links_fr'] = $this->_stripHTMLtags($letter_values['calendar_links_fr']);
        }
        foreach(array('en','fr') as $lang) {
            $cnt=0;
            foreach(array($id_0,$id_1) as $id_list){
                foreach($id_list as $uid => $date){
                    $item = $metaFileData[$uid];
                    $item_values = array();
                    $item_anchor = 'item'.$lang.$cnt;
                    $item_values['item_anchor'] = $item_anchor;
                    $item_values['item_title'] = $item['subject_'.$lang];
                    if($onlineFormat || $inemail){
                        $item_values['item_img'] = $this->_get_img_tag($item['imgfile'],$cnt);
                    } else {
                        $item_values['item_img'] = $this->_get_img_tag($item['imgfile']);
                    }
                    $item_values['item_msg'] =  str_replace("\n",$line_sep,$item['msg_'.$lang]);
                    $item_values['more_link'] = '';
                    $item_values['more_msg'] = '';
                    $link = $item['link_en'];
                    if($lang=='fr' && $item['link_fr']) $link=$item['link_fr'];
                    if($item['msg2_'.$lang] || $link){
                        if($full_desc) {
                            if($item['msg2_'.$lang])
                                $item_values['item_msg'] .=  $line_sep.str_replace("\n",$line_sep,$item['msg2_'.$lang]).$line_sep;
                            if($link)
                                $item_values['item_msg'] .= $line_sep.'['.
                                sprintf(ACCMTL_ELETTER_LINK_FMT2,'morelinkstyle',$link,$link).']';

                        } else  {
                            $item_values['more_link'] = $eletter_link.'#'.$item_anchor;
                            $item_values['more_msg'] = '['.$this->langArray[$lang]['more'].']';
                        }
                    }
                    $item_values['item_msg'] .= $line_sep.
                        $this->_str_replace_from_values('Contact: __from_name__ '.$lt.
                        sprintf(ACCMTL_ELETTER_LINK_FMT2,'emaillinkstyle','mailto:__from_email__','__from_email__').
                        $gt.' __from_phone__',$item);
                    if($txtFormat){
                        foreach($item_values as $k=>$v){
                            $v = $this->_stripHTMLtags($v);
                            $item_values[$k] = $v;
                        }
                    }
                    $item_str = $this->_str_replace_from_values($tpl_item,$item_values);

                    $letter_values['titles_anchor_links_'.$lang] .= sprintf(ACCMTL_ELETTER_LINK_FMT,'#'.$item_anchor,'-&nbsp;'.$item['subject_'.$lang]).$line_sep;
                    if($cnt<$maxtopitems){
                        $letter_values['top_part_items_'.$lang] .= $item_str;
                    }else{
                        $letter_values['bottom_part_items_'.$lang] .= $item_str;
                    }
                    $cnt++;
                }
            }
            foreach(array('cal_nb_wk','news_nb_wk') as $type){
                if(isset($postValues[$type]) && strtolower($postValues[$type]) != 'none'){
                    if($type=='news_nb_wk'){
                        //TODO: make use of new icsshow plugin
                        $mycalObj = new ACC_Calendar_eletter_news();
                        $mycalLink = str_replace('@@lang@@',$lang,ACCMTL_NEWS_URL);
                    }else{
                        //TODO: make use of new icsshow plugin
                        $mycalObj = new ACC_Calendar_eletter_activities();
                        $mycalLink = str_replace('@@lang@@',$lang,ACCMTL_CAL_URL);
                    }
                    $nb_wk = 2;
                    if (is_numeric($postValues[$type])) $nb_wk = $postValues[$type];
                    $newsitem = $mycalObj->getCalSubArray($lang,false,0,$nb_wk*7);
                    foreach($newsitem as $item){
                        $item_values = array();
                        $item_anchor = 'item'.$lang.$cnt;
                        $item_values['item_anchor'] = $item_anchor;
                        $item_values['item_title'] = $item['summary'];
                        $item_values['item_img'] = '';
                        $item_values['item_msg'] =  str_replace("\n","<br />",$item['description_short']);
                        $item_values['more_link'] = $mycalLink.$item['uid'];
                        $item_values['more_msg'] = '['.$this->langArray[$lang]['more'].']';
                        if($txtFormat){
                            foreach($item_values as $k=>$v){
                                $v = $this->_stripHTMLtags($v);
                                $item_values[$k] = $v;
                            }
                        }
                        $item_str = $this->_str_replace_from_values($tpl_item,$item_values);
                        $letter_values['titles_anchor_links_'.$lang] .= sprintf(ACCMTL_ELETTER_LINK_FMT,'#'.$item_anchor,'-&nbsp;'.$item['summary']).'<br />';
                        if($cnt<$maxtopitems){
                            $letter_values['top_part_items_'.$lang] .= $item_str;
                        }else{
                            $letter_values['bottom_part_items_'.$lang] .= $item_str;
                        }
                        $cnt++;
                    }
                }
            }
        }

        $msg = $this->_str_replace_from_values($tpl_letter,$letter_values);

        if($onlineFormat) {
/*
            $msg = '<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head><title>ACC/CAC Montreal eLetter '.date('Y-m-d').'</title>
   <meta http-equiv="content-type" content="application/xhtml+xml;charset=utf-8" />
   <meta http-equiv="content-style-type" content="text/css" />
 </head><body>'
                . $msg .
                '</body></html>';
*/
            $email_css  = @io_readFile(ACCMTL_ELETTER_TPL_CSS,false);
            $msg = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<title>ACC/CAC Montreal eLetter '.date('Y-m-d').'</title>
<meta http-equiv="content-type" content="application/xhtml+xml;charset=utf-8" />
<meta http-equiv="content-style-type" content="text/css" />
</head><body>'
                . $msg .
                '<style type="text/css">'.$email_css.
                '</style>'.
                '<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
_uacct = "UA-1793673-1";
urchinTracker();
</script>'.
                '</body></html>';
        }
        $this->reset = false;
        return $msg;
    }

    /**
     *
     */
    function _admin_submit_produce($postValues,$metaFileData) {
        $online = $this->_admin_submit_preview_produce($postValues,$metaFileData,true);
        $filename = ACCMTL_ELETTER_DIR.$this->_eletter_name();
        @io_SaveFile($filename,$online);

        $email_html = $this->_admin_submit_preview_produce($postValues,$metaFileData,false,false,true);
        $email_text = $this->_admin_submit_preview_produce($postValues,$metaFileData,false,true);
        $email_css  = @io_readFile(ACCMTL_ELETTER_TPL_CSS,false);

        $msg = '<p>Produce Action<br />Copy the content of the box below and past it in <a href=\'http://constantcontact.com\'>ConstantContact.com</a> as html email code.</p>';
        $msg .= '<textarea style=\'height:15em; width:95%; overflow:scroll;"\' readonly=\'readonly\'>';
        $msg .= $email_html;
        $msg .= '</textarea>';
        $msg .= '<p>Copy the content of the box below and past it in <a href=\'http://constantcontact.com\'>ConstantContact.com</a> as text email code.</p>';
        $msg .= '<textarea style=\'height:15em; width:95%; overflow:scroll;"\' readonly=\'readonly\'>';
        $msg .= hsc($email_text);
        $msg .= '</textarea>';
        $msg .= '<p>Copy the content of the box below and past it in <a href=\'http://constantcontact.com\'>ConstantContact.com</a> as Style email code.<br />This should already be part of the template and you would not have to do it... may be good to double check though.</p>';
        $msg .= '<textarea style=\'height:15em; width:95%; overflow:scroll;"\' readonly=\'readonly\'>';
        $msg .= hsc(str_replace('div#acceletter ','',$email_css));
        $msg .= '</textarea>';

        $this->reset = false;
        return $msg;
    }

    function _eletter_name(){
        return 'acc-mtl-eletter-'.date('Y-m-d').'.php';
    }

}

$my_contact_form = new ACC_Form_eletter_admin($this);
print($my_contact_form->_action_show_form());
